#!/bin/bash


function usage()
{
    echo "usage :cmd [params]"
    echo "cmd:"
    echo "  help|-help|--help|-h|--h"
    echo "  disk|mem|top all|host [params]"
    echo "  login host [params]"
}

if (($# < 2)); then
    usage
    exit 1
fi

###########################################################################

login() {
    ip=$1
    ssh $ip
}

disk() {
    ip=$1
    result=`ssh $ip ""df | grep / | awk '{if (\$2 > 20000000) printf("%s\\t%0.1fG\\t%s\\n", \$1, \$2/1024/1024, \$5)}'""`
    ./util/info.sh "$title" "OK" "$result"
}

mem() {
    ip=$1
    result=`ssh $ip "top -bM -n 1 | grep Mem:"`
    echo "[$title] $result"
}

top() {
    ip=$1
    dc=$2
    echo "[$title] top $dc"
    case "$dc" in
        node)
        ssh $ip "top -bM -n 1 | grep node | head -10"
        ;;
        stat)
        ssh $ip "top -bM -n 1 | head -4"
        ;;
        *)
        ssh $ip "top -bM -n 1 | head -16"
        ;;
    esac
}

copy() {
    ip=$1
    file=$2

    scp $file $ip:online/
}

###########################################################################

cd $(dirname $(readlink -f $0));
process=`basename $0`

cmd=$1
dest=$2
title="$cmd $dest"

case "$cmd" in
    help|-help|--help|-h|--h)
        usage
        exit
    ;;
    login|disk|mem|top|copy) ;;
    *)
    ./util/info.sh "cmd $cmd" "unknown"
    usage
    exit 1
esac


if [ "all" == $dest ]; then
    case "$cmd" in
        login)
            ./util/info.sh "$title" "forbidden"
            usage
            exit 1
        ;;
    esac

    hosts=(`./config/get.sh server.all`)
    for host in ${hosts[*]}; do
        ./$process $cmd $host $3 $4 $5
    done
else
    ip=`./config/get.sh server.host.$dest.ip`
    if [ -z $ip ]; then
        ./util/error.sh "$title" "invalid"
        exit 1
    fi
    $cmd $ip $3 $4 $5
fi
